<template>
  <div class="page-main">
    <query-page
      ref="queryPageRef"
      v-model:selectedKeys="selectedKeys"
      :form-component-config="formComponentConfig"
      :form-render-config="newformRenderConfig"
      :form-render-keys="renderKeys"
      :table-component-config="tableComponentConfig"
      :table-render-config="tableRenderConfig"
      :table-render-keys="tableRenderKeys"
      :loading="isLoading"
      :data="renderData"
      :total="total"
      title="采购需求汇总"
      height="calc(100vh - 274px)"
      row-selection-type="checkbox"
      @selection-change="selectionChange"
      @query-data="getData"
    >
      <template #top-container>
        <a-tabs v-model="activeKey" @change="changeKey">
          <a-tab-pane key="finishedProduct" title="成品" />
          <a-tab-pane key="rawMaterial" title="原材料" />
          <a-tab-pane key="standardParts" title="标准件" />
          <a-tab-pane key="spareParts" title="零组件" />
          <a-tab-pane key="forgedCastings" title="锻铸件" />
        </a-tabs>
      </template>
      <template #header-ext-container>
        <a-radio-group
          v-model="position"
          style="margin-top: 16px"
          type="button"
          @change="positionChange"
        >
          <a-radio value="Ling">配套/零星需求</a-radio>
          <a-radio value="All">汇总结果</a-radio>
        </a-radio-group>
      </template>
      <template #container-side>
        <a-space v-if="position === 'Ling'">
          <a-button
            type="primary"
            :disabled="selectedKeys.length === 0"
            @click="handleSummary"
            >批量汇总</a-button
          >
          <a-button
            v-permission="['procurement:require-summary:summary-async']"
            :type="selectedKeys.length === 0 ? 'dashed' : 'outline'"
            :disabled="selectedKeys.length === 0"
            @click="handleSummaryTask"
            >创建汇总任务</a-button
          >
          <a-button
            v-permission="['procurement:require-summary:summary-all']"
            type="outline"
            @click="handleAllSummaryTask"
            >创建全部汇总任务</a-button
          >
          <a-button type="outline" @click="handleDetail">查看任务日志</a-button>
        </a-space>
        <a-space v-else>
          <a-button
            v-permission="['procurement:require-summary:revocation']"
            type="primary"
            :disabled="selectedKeys.length === 0"
            @click="revokeSummary"
            >撤销汇总</a-button
          >
        </a-space>
      </template>
      <template #categoryLv1Name="{ record }">
        {{
          record.categoryLv1Name +
          '/' +
          record.categoryLv2Name +
          '/' +
          record.categoryLv3Name
        }}
      </template>
      <template #deptId="{ record }">
        <depId :dep-id="record.deptId"></depId>
      </template>
      <template #optional="{ record }">
        <a-button
          v-permission="['procurement:require-summary:summary']"
          type="text"
          @click.stop="handleSummary(record)"
          >汇总</a-button
        >
      </template>
    </query-page>
    <Detail v-if="detailShow" v-model:detail-show="detailShow" />
  </div>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import {
    getPage,
    getSummaryPage,
    summary,
    asyncSummary,
    asyncSummaryAll,
    revocation,
  } from '@/api/balance-management/purchase';
  import { Message } from '@arco-design/web-vue';
  import modalPromise from '@/common/utils/modal-promise';
  import queryPage from '@/common/components/query-page/index.vue';
  import depId from './component/depId.vue';
  import {
    formRenderConfig,
    formComponentConfig,
  } from './form-comp/base-form-config';
  import {
    tableRenderConfig,
    tableComponentConfig,
  } from './table-comp/base-table-config';

  import Detail from './component/detail.vue';
  import baseRenderKeys from './table-comp/render-table-columns';
  import formRender from './form-comp/form-render';
  // 当前表格要渲染哪些值
  const tableRenderKeys = ref<any[]>([]);
  const mdsItemType = ref(2);
  const activeKey = ref('finishedProduct');
  const tabObj = ref({});
  const position = ref('Ling');
  const detailShow = ref(false);
  const renderData = ref<any[]>([]);
  const isLoading = ref(true);
  const total = ref(0);
  const selectedKeys = ref([]);
  const selection = ref<any[]>([]);
  const newformRenderConfig = ref({});
  newformRenderConfig.value = formRenderConfig(mdsItemType);
  tabObj.value = formRender;
  const init = () => {
    const key = `${activeKey.value}${position.value}`;
    console.log('baseRenderKeys[key]', baseRenderKeys[key]);
    tableRenderKeys.value = baseRenderKeys[key];
  };
  init();
  const renderKeys = ref<any>([]);

  renderKeys.value = tabObj.value.finishedProduct;
  const mdsItemTypeList = ref({
    finishedProduct: 2,
    rawMaterial: 3,
    standardParts: 1,
    spareParts: 4,
    forgedCastings: 5,
  });
  const handleAllSummaryTask = async () => {
    try {
      await modalPromise.info({
        title: '请确认',
        content: '您确定要汇总所有数据?',
        hideCancel: false,
      });
    } catch {
      return;
    }
    const params = {
      classType: mdsItemType.value,
    };
    const data = await asyncSummaryAll(params);
    if (data.code === 200) {
      Message.success('汇总成功');
      getData();
    } else {
      Message.warning(data.data);
    }

    // Modal.info({
    //   title: '请确认',
    //   content: '您确定要汇总所有数据?',
    //   hideCancel: false,
    //   onOk: async () => {
    //     const params = {
    //       classType: mdsItemType.value,
    //     };
    //     const data = await asyncSummaryAll(params);
    //     if (data.code === 200) {
    //       Message.success('汇总成功');
    //       getData();
    //     } else {
    //       Message.warning(data.data);
    //     }
    //   },
    // });
  };
  const selectionChange = () => {
    selection.value = renderData.value.filter((item: any) => {
      return selectedKeys.value.includes(item.id);
    });
  };
  const changeKey = (data: any) => {
    clearSelectKeys();
    mdsItemType.value = mdsItemTypeList.value[data];
    activeKey.value = data;
    renderKeys.value = tabObj.value[data];
    position.value = 'Ling';
    init();
    getData();
  };
  const handleSummaryTask = async (val) => {
    try {
      await modalPromise.info({
        title: '请确认',
        content: '您确定要汇总当前所选的数据?',
        hideCancel: false,
      });
    } catch {
      return;
    }
    const params = {
      classType: mdsItemType.value,
      ids: val.id ? [val.id] : selectedKeys.value,
    };
    const data = await asyncSummary(params);
    if (data.code === 200) {
      Message.success('汇总成功');
      getData();
    } else {
      Message.warning(data.data);
    }
    // Modal.info({
    //   title: '请确认',
    //   content: '您确定要汇总当前所选的数据?',
    //   hideCancel: false,
    //   onOk: async () => {
    //     const params = {
    //       classType: mdsItemType.value,
    //       ids: val.id ? [val.id] : selectedKeys.value,
    //     };
    //     const data = await asyncSummary(params);
    //     if (data.code === 200) {
    //       Message.success('汇总成功');
    //       getData();
    //     } else {
    //       Message.warning(data.data);
    //     }
    //   },
    // });
  };
  const handleSummary = async (val) => {
    try {
      await modalPromise.info({
        title: '请确认',
        content: '您确定要汇总当前所选的数据?',
        hideCancel: false,
      });
    } catch {
      return;
    }
    const params = {
      classType: mdsItemType.value,
      ids: val.id ? [val.id] : selectedKeys.value,
    };
    const data = await summary(params);
    if (data.code === 200) {
      Message.success('汇总成功');
      selectedKeys.value = [];
      getData();
    } else {
      Message.warning(data.data);
    }

    // Modal.info({
    //   title: '请确认',
    //   content: '您确定要汇总当前所选的数据?',
    //   hideCancel: false,
    //   onOk: async () => {
    //     const params = {
    //       classType: mdsItemType.value,
    //       ids: val.id ? [val.id] : selectedKeys.value,
    //     };
    //     const data = await summary(params);
    //     if (data.code === 200) {
    //       Message.success('汇总成功');
    //       selectedKeys.value = [];
    //       getData();
    //     } else {
    //       Message.warning(data.data);
    //     }
    //   },
    // });
  };
  const getData = async (queryInfo: any = {}) => {
    try {
      isLoading.value = true;
      const params = {
        functionType: 0,
        classType: mdsItemType.value,
        mergeState: position.value === 'Ling' ? 0 : null,
        closeState: position.value === 'Ling' ? 0 : null,
        confirmState: position.value === 'Ling' ? 1 : null,
        ...queryInfo,
      };
      console.log(' ---------------- ', position.value === 'Ling');
      const { data } =
        position.value === 'Ling'
          ? await getPage(params)
          : await getSummaryPage(params);
      if (data) {
        console.log('data', data);
        total.value = data.total;
        renderData.value = [...data.list];
        selectedKeys.value = [];
      }
      isLoading.value = false;
    } catch (error) {
      Message.warning({
        content: error,
      });
    }
  };
  const revokeSummary = async () => {
    try {
      await modalPromise.info({
        title: '请确认',
        content: '您确定要撤销当前所选的汇总数据?',
        hideCancel: false,
      });
    } catch {
      return;
    }
    const requireNoArr = selectedKeys.value.map((item) => {
      const res = renderData.value.find((v) => v.id === item);
      return res.requireNo;
    });
    const params = {
      classType: mdsItemType.value,
      requireNoList: requireNoArr,
    };
    const data = await revocation(params);
    if (data.code === 200) {
      Message.success('撤销成功');
      selectedKeys.value = [];
      getData();
    } else {
      Message.warning(data.data);
    }
    // Modal.info({
    //   title: '请确认',
    //   content: '您确定要撤销当前所选的汇总数据?',
    //   hideCancel: false,
    //   onOk: async () => {
    //     const requireNoArr = selectedKeys.value.map((item) => {
    //       const res = renderData.value.find((v) => v.id === item);
    //       return res.requireNo;
    //     });
    //     const params = {
    //       classType: mdsItemType.value,
    //       requireNoList: requireNoArr,
    //     };
    //     const data = await revocation(params);
    //     if (data.code === 200) {
    //       Message.success('撤销成功');
    //       selectedKeys.value = [];
    //       getData();
    //     } else {
    //       Message.warning(data.data);
    //     }
    //   },
    // });
  };
  const handleDetail = () => {
    detailShow.value = true;
  };
  const clearSelectKeys = () => {
    selectedKeys.value = [];
  };
  const positionChange = (val) => {
    clearSelectKeys();
    position.value = val;
    init();
    getData();
  };
</script>

<style lang="less" scoped>
  .page-con {
    height: 100%;
    margin: 16px;
    padding: 12px 24px;
    background-color: #fff;
  }

  /deep/ .arco-radio-group-button {
    width: 100%;
  }

  /deep/ .arco-radio-button {
    width: 50%;
    color: #4e5769 !important;
    text-align: center;
  }

  /deep/ .arco-radio-button.arco-radio-checked {
    color: #1e2228 !important;
  }

  .arco-btn-outline {
    color: #1e2228 !important;
    border-color: #d9dee7 !important;
  }
</style>
